<template>
    <el-dialog v-model="show" title="分配权限" @close="handleClose" width="400px">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="操作">
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        </el-form-item>
  
        <el-form-item label="分配权限">
          <el-tree
            ref="treeRef"
            :data="menuList"
            :props="{ label: 'name' }"
            node-key="id"
            show-checkbox
            :key="treeKey"
          />
        </el-form-item>
      </el-form>
  
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, nextTick } from 'vue'
  import { updateRoleApi, getMenuListApi } from '@/api/auth'
  import { ElMessage, type TreeInstance } from 'element-plus'
  
  const show = ref(false)
  const emit = defineEmits(['success'])
  const treeRef = ref<TreeInstance>()
  const treeKey = ref(0) // ✅ 每次打开用来强制刷新 el-tree
  
  const formData = ref({
    id: 0,
    name: '',
    remarks: '',
    rules: []
  })
  
  const menuList = ref<any[]>([])
  const checkAll = ref(false)
  
  const getMenuLists = async () => {
    const { data } = await getMenuListApi({})
    menuList.value = JSON.parse(JSON.stringify(data)) // ✅ 深拷贝避免引用污染
  }
  
  // 全选事件
  const handleCheckAllChange = () => {
    const allIds = getAllIds(menuList.value)
    treeRef.value?.setCheckedKeys(checkAll.value ? allIds : [])
  }

  // 递归获取所有 ID
  const getAllIds = (list: any[]): number[] => {
    const ids: number[] = []
    const walk = (nodes: any[]) => {
      nodes.forEach(node => {
        ids.push(node.id)
        if (node.children?.length) walk(node.children)
      })
    }
    walk(list)
    return ids
  }
  
  const handleSubmit = async () => {
    const checkedKeys = treeRef.value!.getCheckedKeys()
    const res:any = await updateRoleApi({
      id: formData.value.id,
      name: formData.value.name,
      rules: checkedKeys
    })
    ElMessage.success(res.message)
    handleClose()
    emit('success')
  }
  
  const handleClose = () => {
    show.value = false
  }
  
  // 处理打开表单
  const getDetails = (data: any) => {
    if (data) {
      formData.value = { ...formData.value, ...data }
    } else {
      formData.value = {
        id: 0,
        name: '',
        remarks: '',
        rules: []
      }
    }
  }
  
  // 暴露方法
  defineExpose({
    open() {
      show.value = true
      treeKey.value++ // ✅ 强制刷新 tree
      getMenuLists().then(() => {
        // 等 DOM 更新完后再设置勾选状态
        nextTick(() => {
          treeRef.value?.setCheckedKeys(formData.value.rules)
        })
      })
    },
    setFormData(data: any) {
      getDetails(data)
    }
  })
  </script>
  
<style scoped>
  /* 弹窗样式 */
  :deep(.el-dialog) {
    background: #ffffff !important;
    border: 1px solid #e5e7eb !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
    border-radius: 16px !important;
    overflow: hidden !important;
  }

  :deep(.el-dialog__header) {
    background: #f9fafb !important;
    border-bottom: 1px solid #e5e7eb !important;
    padding: 20px 24px !important;
  }

  :deep(.el-dialog__title) {
    color: #1e293b !important;
    font-size: 18px !important;
    font-weight: 600 !important;
  }

  :deep(.el-dialog__body) {
    padding: 24px !important;
    background: #ffffff !important;
    max-height: 400px !important;
    overflow-y: auto !important;
  }

  :deep(.el-dialog__footer) {
    background: #f9fafb !important;
    border-top: 1px solid #e5e7eb !important;
    padding: 16px 24px !important;
    display: flex !important;
    justify-content: flex-end !important;
    gap: 12px !important;
  }

  /* 表单样式 */
  :deep(.el-form) {
    position: relative !important;
    z-index: 2 !important;
  }

  :deep(.el-form-item) {
    margin-bottom: 20px !important;
    position: relative !important;
  }

  :deep(.el-form-item__label) {
    color: #475569 !important;
    font-weight: 500 !important;
    font-size: 14px !important;
    text-align: right !important;
  }

  /* 复选框样式 */
  :deep(.el-checkbox) {
    color: #475569 !important;
    font-size: 14px !important;
  }

  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #667eea !important;
    border-color: #667eea !important;
  }

  :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
    color: #1e293b !important;
    font-weight: 500 !important;
  }

  :deep(.el-checkbox__inner) {
    border-radius: 4px !important;
    transition: all 0.3s ease !important;
  }

  :deep(.el-checkbox__input:hover .el-checkbox__inner) {
    border-color: #667eea !important;
  }

  /* 树形组件样式 */
  :deep(.el-tree) {
    background: #ffffff !important;
    border: none !important;
  }

  :deep(.el-tree-node) {
    padding: 4px 0 !important;
  }

  :deep(.el-tree-node__content) {
    height: 36px !important;
    line-height: 36px !important;
    border-radius: 6px !important;
    transition: all 0.3s ease !important;
  }

  :deep(.el-tree-node__content:hover) {
    background-color: #f9fafb !important;
  }

  :deep(.el-tree-node__label) {
    color: #475569 !important;
    font-size: 14px !important;
  }

  :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
    background-color: #eff6ff !important;
    color: #667eea !important;
  }

  :deep(.el-tree-node__expand-icon) {
    color: #9ca3af !important;
    transition: color 0.3s ease !important;
  }

  :deep(.el-tree-node__expand-icon:hover) {
    color: #667eea !important;
  }

  /* 按钮样式 */
  :deep(.el-dialog__footer .el-button:first-child) {
    background: #ffffff !important;
    border-color: #d1d5db !important;
    color: #6b7280 !important;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
    transition: all 0.3s ease !important;
    border-radius: 8px !important;
    padding: 8px 20px !important;
  }

  :deep(.el-dialog__footer .el-button:first-child:hover) {
    border-color: #6b7280 !important;
    box-shadow: 0 2px 5px rgba(107, 114, 128, 0.15) !important;
    transform: translateY(-1px) !important;
  }

  :deep(.el-dialog__footer .el-button:last-child) {
    background: #667eea !important;
    border-color: #667eea !important;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3) !important;
    transition: all 0.3s ease !important;
    border-radius: 8px !important;
    padding: 8px 20px !important;
  }

  :deep(.el-dialog__footer .el-button:last-child:hover) {
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4) !important;
    transform: translateY(-1px) !important;
  }

  :deep(.el-dialog__footer .el-button:last-child.is-loading) {
    box-shadow: 0 1px 3px rgba(102, 126, 234, 0.1) !important;
  }
</style>
  